<template>
  <div id="user-settings-profile-avatar" class="setting-avatar">
    <el-avatar class="avatar" :size="160" :src="avatarUrl"></el-avatar>
    <div class="options">
      <h5>上传新头像</h5>
      <UploadAvatar class="m-b-10" :preview-url.sync="avatarUrl" v-on:avatar="setAvatar" />
      <p class="info">仅支持 jpg, jpeg, png 格式的图片类型。<br>图片允许的最大大小为2MB。</p>
      <el-divider/>
      <div>
        <el-button size="small" type="primary" :disabled="!avatarKey"
                   @click="onSubmit" :loading="isLoading">保存新头像</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import UploadAvatar from '@/components/shared/UploadAvatar';
import * as format from '../../format';

export default {
  name: 'PublicAvatar', // 用户资料的头像设置
  components: { UploadAvatar },
  data() {
    return {
      avatarUrl: this.$store.state.currentUser.avatar,
      avatarKey: '', // 后端需要的文件key
      isLoading: false, // 正在保存新头像
    };
  },
  computed: {
    // 更新头像所需参数
    initUpdateParams() {
      return {
        userId: this.$store.state.currentUser.id,
        avatarKey: this.avatarKey,
      };
    },
  },
  methods: {
    // 接受上传组件返回的头像数据
    setAvatar(avatar) {
      this.avatarUrl = avatar.url;
      this.avatarKey = avatar.key;
    },
    // 保存
    onSubmit() {
      this.isLoading = true;
      this.$api.users.update(this.initUpdateParams)
        .then((res) => {
          this.$message.success('头像保存成功');
          this.handleRes(res);
        })
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
    // 处理返回的信息（这里是重新保存，返回的信息中没有token）
    handleRes(res) {
      const formatUser = format.formatUser(res.data); // 处理信息
      const user = Object.assign(formatUser, { token: this.$store.state.currentUser.token });
      this.$store.dispatch('setCurrentUser', user);
    },
  },
};
</script>

<style></style>
